// 一个数组，能构成最大和的子数组找出来

const arr = [-2, 2, -3, 4, -1, 2, 1, -5, 3]

// const getMaxSubArray = (arr) => {
//   let max = arr[0]
//   let newMax = arr[0]

//   for (let i = 0; i < arr.length; i++) {
//     newMax = Math.max(newMax + arr[i], arr[i])
//     max = Math.max(max, newMax)
//   }
//   return max
// }

const getMaxSubArray = (arr) => {

  let max = arr[0]
  let newMax = arr[0]

  let start = 0, end = 0, tempStart = 0

  for (let i = 1; i < arr.length; i++) {
    if (newMax + arr[i] < arr[i]) {
      newMax = arr[i]
      tempStart = i
    } else {
      newMax += arr[i]
    }

    if (newMax > max) {
      max = newMax;
      start = tempStart;
      end = i;
    }
  }

  return arr.slice(start, end + 1);
}

console.log(getMaxSubArray(arr));
